package com.happyelements.resource
{
	import flash.events.IOErrorEvent;
	import flash.system.ApplicationDomain;
	import flash.utils.Dictionary;
	
	import mx.core.Singleton;

	/**
	 *
	 * @author Steven
	 *
	 */
	public class ResourceManager
	{
		private static var _instance:ResourceManager;
		
		private const _dict:Dictionary = new Dictionary(true);
		
		private const _callbackDict:Dictionary = new Dictionary(true);
		
		public static function get instance():ResourceManager
		{
			_instance || (_instance = new ResourceManager(new Singleton()));
			
			return _instance;
		}
		
		public function ResourceManager(lock:Singleton)
		{
			if (! lock)
			{
				throw new Error("-");
			}
		}
		
		public function getResourceByURL(url:String, complete:Function, error:Function):void
		{
			if (_dict[url] is ApplicationDomain)
			{
				complete(_dict[url]);
			}
			else
			{
				getCallbackRecord(url).push(new Callback(complete, error));
				
				if (! _dict[url])
				{
					_dict[url] = true;
					
					var animationLoader:AnimationLoader = new AnimationLoader(url, function(applicationDomain:ApplicationDomain):void
					{
						_dict[url] = applicationDomain;
						
						for each (var callback:Callback in getCallbackRecord(url))
						{
							callback.complete(applicationDomain);
						}
						
						delete _callbackDict[url];
					}, 
						function(url:String, event:IOErrorEvent):void
						{ 
							for each (var callback:Callback in getCallbackRecord(url))
							{
								callback.error(url, event);
							}
							
							delete _callbackDict[url];
						}
					);
					
					animationLoader.load();
				}
			}
		}
		
		private function getCallbackRecord(url:String):Vector.<Callback>
		{
			return _callbackDict[url] || (_callbackDict[url] = new Vector.<Callback>());
		}
	}
}

class Callback
{
	public var complete:Function;
	
	public var error:Function;
	
	public function Callback(complete:Function, error:Function)
	{
		this.complete = complete;
		this.error = error;
	}
}

class Singleton
{
	
}